# -*- coding:utf-8 -*-

import uuid, MySQLdb, traceback
from server.util import logs
from DBUtils.PersistentDB import PersistentDB
from twisted.internet import defer

parm = ('192.168.1.5', 3306, 'root', 'w111111', 'RWLS', 'utf8')


def crossroads(func):
    def wrapper(*args, **kwargs):
        result = None
        d = defer.Deferred()
        d.addCallbacks(args[0]._close, args[0]._rollback)
        try:
            args[0].__init__()
            result = func(*args, **kwargs)
        except IOError, io:
            d.errback(io)
        finally:
            d.callback(1)

        return result

    return wrapper


class DBService:
    __pool = None

    def __init__(self, args=()):
        try:
            self.conn = self.__getConn(args)
            self.cursor = self.conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
        except Exception, e:
            print traceback.format_exc()
            print e

    def __del__(self):
        self.cursor.close()
        self.conn.close()

    def __getConn(self, args):
        if self._DBService__pool is None:
            self._DBService__pool = PersistentDB(creator=MySQLdb, maxusage=10, host=parm[0], port=parm[1], user=parm[2], passwd=parm[3], db=parm[4], charset=parm[5])
        return self._DBService__pool.connection()

    def _close(self, arg):
        self.cursor.close()
        self.conn.close()

    def _rollback(self, message):
        self.conn.rollback()
        self.conn.close()
        raise traceback.format_exc()

    @crossroads
    # @logs.logged("DEBUG")
    def select(self, sql):
        self.cursor.execute(sql)
        self.conn.commit()
        return self.cursor.fetchall()

    @crossroads
    # @logs.logged("DEBUG")
    def insert(self, *sqls):
        for sql in sqls:
            self.cursor.execute(sql)
        self.conn.commit()

    @crossroads
    # @logs.logged("DEBUG")
    def update(self, *sqls):
        for sql in sqls:
            self.cursor.execute(sql)
        self.conn.commit()

    @crossroads
    # @logs.logged("DEBUG")
    def delete(self, *sqls):
        for sql in sqls:
            self.cursor.execute(sql)
        self.conn.commit()

    @crossroads
    def callproc(self, name, args):
        self.cursor.execute("call %s('%s', '%s', %s)" % (name, args[0], args[1], args[2]) )
        self.conn.commit()